<?php
namespace app\tools\logic;
use think\facade\Db;

class ChannelApiLogic{
	static function getList(){
		$channel_id = input('channel_id','');
		if(!$channel_id){
			return ['code'=>125];
		}
		$info = Db::name('channel')->where('id', $channel_id)->find();
		if(!$info){
			return ['code'=>128];
		}
		$cof = config();
    	$apiCnf = $cof['dgfw']['channel'];
		if(!$apiCnf || !$apiCnf['functions']){
			return ['code'=>136];
		}
		$list = Db::name('channel_function')->where('channel_id', $channel_id)->select()->toArray();
		foreach($apiCnf['functions'] as $kk => $vv){
			foreach($list as $v){
				if($vv['function']==$v['function']){
					$apiCnf['functions'][$kk]['url'] = $v['url'];
					$apiCnf['functions'][$kk]['params'] = $v['params'];
					break;
				}
			}
		}
		return ['code'=>0,'data'=>$apiCnf];

	}
	static function save(){
		$channel_id = input('channel_id','');
		if(!$channel_id){
			return 125;
		}

		$info = Db::name('channel')->where('id', $channel_id)->find();
		if(!$info){
			return 128;
		}

		$functions = input('functions',[]);
		if(!$functions){
			return 135;
		}

		//获取通道配置的静态信息
		$cof = config();
    	$apiCnf = $cof['dgfw']['channel'];
		if(!$apiCnf || !$apiCnf['functions']){
			return 136;
		}

		foreach($functions as $v){
			$data = [];
			$data['channel_id'] = $channel_id;
			$data['function'] = $v['function'];
			$data['url'] = $v['url'];
			$data['params'] = $v['params'];

			$hasChange = 1;
			foreach($apiCnf['functions'] as $vv){
				if($vv['function']==$v['function']){
					$hasChange = 0;
					break;
				}
			}

			//function被改变，直接返回，不做处理
			if($hasChange==1){
				return 137;
			}


			$info = Db::name('channel_function')
						->field('id')
						->where('channel_id', $channel_id)
						->where('function', $v['function'])
						->find();
			if($info){
				Db::name('channel_function')->where('id', $info['id'])->update($data);
			}else{
				Db::name('channel_function')->insert($data);
			}
		}
		return 0;
	}
}
